//
//  SANetManager.m
//  Saas
//
//  Created by bing on 2019/12/31.
//  Copyright © 2019 bing. All rights reserved.
//

#import "SANetManager.h"
#import "AFHTTPSessionManager.h"
#import "SALoginVC.h"
#import "SAUserInfoTool.h"

NSInteger const kAFNetworkingTimeoutInterval = 30;

@implementation SANetManager

static AFHTTPSessionManager *aManager;


+ (AFHTTPSessionManager *)sharedAFManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        aManager = [AFHTTPSessionManager manager];
        //以下三项manager的属性根据需要进行配置
    });
    return aManager;
}

+ (void)requestWithType:(SkyHttpRequestType)type
              urlString:(NSString *)urlString
             parameters:(NSDictionary *)parameters
           successBlock:(SkyHTTPRequestSuccessBlock)successBlock
           failureBlock:(SkyHTTPRequestFailedBlock)failureBlock
{
    if (urlString == nil)
    {
        return;
    }
    
    if (@available(iOS 9.0, *)) {
        urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    
    if (type == SkyHttpRequestTypeGet)
    {
        AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes  = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
        [AFJSONResponseSerializer serializer].removesKeysWithNullValues = YES;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        
        //请求方式
        [request setHTTPMethod:@"GET"];
        
        //请求头
        [request setValue:[SAUserInfoTool getModel].token forHTTPHeaderField:@"apix-key"];
        
        [manager GET:urlString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            if ([responseObject isKindOfClass:[NSDictionary class]]) {//普通返回结果
                NSDictionary *dict = (NSDictionary *)responseObject;
                if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"0"]) {
                    successBlock(responseObject[@"data"]);
                }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"901"])
                {
                    //登陆失败
                    SALoginVC *login = [SALoginVC new];
                    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:login];
                    [[UIApplication sharedApplication].keyWindow setRootViewController:navi];
                }else
                {
                    
                    failureBlock(responseObject[@"msg"]);
                }
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failureBlock(@"网络不给力，请稍后重试或检查网络设置");
        }];
        
        
        
        //        [manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        //
        //        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //
        //         NSLog(@"%@",responseObject);
        //           if ([responseObject isKindOfClass:[NSDictionary class]]) {//普通返回结果
        //              NSDictionary *dict = (NSDictionary *)responseObject;
        //              if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"0"]) {
        //                  successBlock(responseObject[@"data"]);
        //              }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"901"])
        //              {
        //                  //登陆失败
        //                  SALoginViewController *login = [SALoginViewController new];
        //                   UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:login];
        //                   [[UIApplication sharedApplication].keyWindow setRootViewController:navi];
        //              }else
        //              {
        //
        //                   failureBlock(responseObject[@"msg"]);
        //              }
        //
        //           }
        //
        //
        //        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //
        //             failureBlock(@"网络不给力，请稍后重试或检查网络设置");
        //        }];
        
    }
    
    if (type == SkyHttpRequestTypePost)
    {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.securityPolicy.allowInvalidCertificates = YES;
        manager.securityPolicy.validatesDomainName = NO;
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlString parameters:nil error:nil];
        
        
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        NSString* token = [[NSUserDefaults standardUserDefaults] stringForKey:@"token"];
        if (token.length > 0) {
            token = [token stringByRemovingPercentEncoding];
            [request setValue:token forHTTPHeaderField:@"authorization"];
        }
        
        NSData *body =  [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
        [request setHTTPBody:body];
        
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
        responseSerializer.removesKeysWithNullValues = YES;
        manager.responseSerializer = responseSerializer;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
        request.timeoutInterval = kAFNetworkingTimeoutInterval;
        
        [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"%@",responseObject);
                
                if ([responseObject isKindOfClass:[NSDictionary class]]) {//普通返回结果
                    NSDictionary *dict = (NSDictionary *)responseObject;
                    if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"0"]) {
                        successBlock(responseObject[@"data"]);
                    }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"901"])
                    {
                        //登陆失败
                        SALoginVC *login = [SALoginVC new];
                        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:login];
                        [[UIApplication sharedApplication].keyWindow setRootViewController:navi];
                    }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"20007"])
                    {
                        NSDictionary *dict1 = @{@"message":dict[@"message"]};
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"message" object:nil userInfo:dict1];
                    }else
                    {
                        // NSLog(@"%@",responseObject[@"msg"]);
                        failureBlock(responseObject[@"msg"]);
                        
                    }
                    
                }
                
            } else {
                
                failureBlock(@"网络不给力，请稍后重试或检查网络设置");
            }
        }]resume];
        
    }
}

+ (void)postDataWithUrl:(NSString *)url params:(NSMutableDictionary *)params imageDatas:(NSArray *)images success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet　setWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/xml",@"text/plain",nil]];
    
    [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (UIImage *image in images) {
            // 图片太大会上传不到服务器上面去
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
            /*
             此方法参数
             1. 要上传的[二进制数据]
             2. 对应网站上[upload.php中]处理文件的[字段"file"]
             3. 要保存在服务器上的[文件名]
             4. 上传文件的[mimeType]
             */
            NSUInteger index = [images indexOfObject:image];
            if (index == images.count-1) {
                // 上传位置图片data
                [formData appendPartWithFileData:imageData name:@"upload_file" fileName:fileName mimeType:@"image/png"];
            } else {
                [formData appendPartWithFileData:imageData name:@"upload_file" fileName:fileName mimeType:@"image/png"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

+ (void)postSingleWithUrl:(NSString *)url params:(NSMutableDictionary *)params imageDatas:(NSString *)images success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet　setWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/xml",@"text/plain",nil]];
    
    [manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 图片太大会上传不到服务器上面去
        NSData *imageData = UIImageJPEGRepresentation(images, 0.5);
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        /*
         此方法参数
         1. 要上传的[二进制数据]
         2. 对应网站上[upload.php中]处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}


+(void)cancelDataTask
{
    NSMutableArray *dataTasks = [NSMutableArray arrayWithArray:[self sharedAFManager].dataTasks];
    for (NSURLSessionDataTask *taskObj in dataTasks) {
        [taskObj cancel];
    }
}

#pragma mark 下载图片
+(void)Download:(NSString *)url successBlock:(SkyHTTPRequestSuccessBlock)successBlock{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSString *name = [[response suggestedFilename] stringByRemovingPercentEncoding];
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *newName = [NSString stringWithFormat:@"%0.f%@",time,name];
        return [documentsDirectoryURL URLByAppendingPathComponent:newName];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSString *newUrl = filePath.absoluteString;
        NSDictionary *dic = @{@"filePath" : newUrl};
        successBlock(dic);
    }];
    [downloadTask resume];
}

@end
